<template>
  <div class="test-container page-container">
    <!-- 搜索选项 -->
    <el-row class="M-B-5" ref="searchRef">
      <el-form :inline="true" class="form" v-model="searchForm">
        <el-form-item class="Form-Item" label="">
          <el-select v-model="searchForm.status" style="width:150px;" placeholder="请选择状态" clearable>
              <el-option v-for="(item,index) in statusDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="Form-Item" label="">
          <el-select v-model="searchForm.gender" style="width:150px;" placeholder="请选择性别" clearable>
              <el-option v-for="(item,index) in genderDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="Form-Item" label="">
          <el-select v-model="searchForm.timeType" style="width:100px;" placeholder="时间类型" clearable>
              <el-option v-for="(item,index) in timeTypeDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
            </el-select>
          <el-date-picker v-model="searchForm.sumTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item class="Form-Item" label="">
          <el-input class="W-Search" v-model="searchForm.searchWord"  placeholder="请输入关键词搜索" clearable >
            <template #prepend>
            <el-select v-model="searchForm.searchType" style="width:100px;" placeholder="关键词" clearable>
              <el-option v-for="(item,index) in searchTypeDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
            </el-select>
            </template>
          </el-input>
        </el-form-item>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
      </el-form>
    </el-row>
    <!-- 按钮组 -->
    <el-row class="M-B-5" ref="btnsRef">
      <el-button type="primary" @click="add('ADD')">添加用户</el-button>
      <el-button type="primary" @click="batchChange">批量启/禁用</el-button>
      <el-button type="danger" @click="batchDel" >批量删除</el-button>
    </el-row>
    <!-- 表格 -->
    <el-row class="M-B-5" >
      <el-table :data="tableData" stripe style="width: 100%" border highlight-current-row :height="tableHeight" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="(item,index) in tableCols" :key="index" :prop="item.prop" :label="item.label" :min-width="item.minWidth">
          <template  #default="scope">
            <!-- 性别 -->
            <div v-if="item.prop=='gender'">{{ scope.row.gender == 1?'男':scope.row.gender == 2?'女':'未知' }}</div>
            <!-- 状态 -->
            <div v-if="item.prop=='status'">
              <el-tag class="M-R-5" :type="scope.row.status==1?'success':'info'">{{scope.row.status==1?'正常':'黑名单'}}</el-tag>
            </div>
            <!-- 操作 -->
            <div v-if="item.prop=='handle'">
              <el-button size="small" type="primary" @click="handleEdit(scope)">编辑</el-button>
              <el-button size="small" :type="scope.row.status==2?'warning':'info'" @click="batchChange(scope.$index, scope.row)">{{scope.row.status==2?'启用':'禁用'}}</el-button>
              <el-button size="small" type="danger" @click="batchDel(scope.$index, scope.row)" >删除</el-button>
            </div>
            <!-- 角色 -->
            <div v-if="item.prop=='roles'">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="getRoleNames(scope.row.roles)"
                placement="bottom"
              >
              <div class="P-Line-1">{{getRoleNames(scope.row.roles)}}</div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- 分页 -->
    <el-row ref="pageRef">
      <el-pagination
      :total="pageTotal"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :background="pageBackground"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </el-row>
    <addUser ref="addUserRef" @RefreshListEmit ="reset"/>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref,reactive ,toRefs ,onMounted,nextTick,defineAsyncComponent } from 'vue'
import { getUsersApi,deleteUsersApi,changeStatusApi } from '@/request/user'
import { rolelistApi } from '@/request/role'
import { getCurrentInstance} from 'vue'
import {useStore} from '@/store'
import user from '@/config/Enums/user'
import Pinterface from '@/config/Interface/Public'
import Interface from '@/config/Interface/User'
import addUser from '@/components/user/addUser.vue'
export default defineComponent({
  name: 'Vuex',
  components:{addUser},
  setup() {
    const context = getCurrentInstance()?.appContext.config.globalProperties; //获取this
    const store = useStore()
    const reactiveData = reactive<Interface.userReactiveData>({
      // 表单
      searchForm:{
        status:'',
        searchWord:'',
        searchType:'',
        gender:'',
        timeType:'',
        sumTime:['',''],
      },
      // 表头
      tableCols:[
        {prop:'username',label:'用户名',minWidth:100},
        {prop:'gender',label:'性别',minWidth:63},
        {prop:'mobile',label:'联系方式',minWidth:125},
        {prop:'email',label:'邮箱',minWidth:168},
        {prop:'status',label:'状态',minWidth:80},
        {prop:'roles',label:'角色',minWidth:60},
        {prop:'create_time',label:'创建时间',minWidth:168},
        {prop:'update_time',label:'更新时间',minWidth:168},
        {prop:'last_login_time',label:'最后登录时间',minWidth:168},
        {prop:'handle',label:'操作',minWidth:200},
      ],
      // 表格数据项
      tableData:[],
      //下拉
      searchTypeDrop:context?.$enums.GetEnumArr(user.SearchTypeDrop),
      statusDrop:context?.$enums.GetEnumArr(user.StatusDrop),
      genderDrop:context?.$enums.GetEnumArr(user.GenderDrop),
      timeTypeDrop:context?.$enums.GetEnumArr(user.timeTypeDrop)
    })
    // 获取用户列表
    const getUserList = async () =>{
      const postData = {
        searchWord:reactiveData.searchForm.searchWord,
        searchType:reactiveData.searchForm.searchType,
        status:reactiveData.searchForm.status,
        gender:reactiveData.searchForm.gender,
        timeType:reactiveData.searchForm.timeType,
        sumTime:reactiveData.searchForm.sumTime,
        currentPage:currentPage.value,
        pageSize:pageSize.value,
      }
      const res = await getUsersApi(postData)
      if(res.data.code === 1){
        reactiveData.tableData = res.data.data.data
        pageTotal.value = res.data.data.total
      }
    }

    // 角色列表
    const roleList = ref<any[]>([])

    // 获取角色列表
    const getRoleList = async () => {
      const postData = {
        searchWord:'',
        searchType:1
      }
      const res = await rolelistApi(postData)
      if(res.data.code === 1 ){
        roleList.value = res.data.data
      }

    }
    // 角色id转名称
    const getRoleNames = (roles:any[]) => {
      const roleNames:string[] = []
      if(roleList.value.length){
        const ids = roles.map((item:any)=>(item.role_id))
        ids.forEach((item:any)=>{
          roleList.value.forEach(data=>{
            if(item===data.id){
              roleNames.push(data.name)
            }
          })
        })
      }
      return roleNames.join(',')
    }

    // 搜索
    const search = ()=>{
      getUserList()
    }
    // 重置
    const reset = () =>{
      reactiveData.searchForm = new Interface.searchForm()
      currentPage.value = 1;
      search()
    }

    // dom节点
    const searchRef = ref();
    const btnsRef = ref();
    const pageRef = ref();

    //表格高度
    const tableHeight = ref(0);

    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageTotal = ref(0)
    const pageBackground = ref(false)

    // 切换表格显示条数
    const handleSizeChange = (val: number) => {
      pageSize.value= val;
      getUserList()
    }
    
    // 切换页码
    const handleCurrentChange = (val: number) => {
      currentPage.value = val
      getUserList()
    }

    // 获取表格高度
    const getTableHeight = ()=>{
      nextTick(()=>{
        if(store!==undefined){
          tableHeight.value = context?.$utils.getTableHeight(store.state.cardHeight,[searchRef.value.$el,btnsRef.value.$el,pageRef.value.$el])
        }else{
          tableHeight.value = 653;
        }
      })
    }

    //表格多选列表
    const selections = ref<any[]>([])
    const handleSelectionChange = (val: Interface.tableData[]) => {
      selections.value = val
    }
    const addUserRef = ref()
    // 创建
    const add = (Type:string,scope?:any) => {
      addUserRef.value.trigger(Type,scope)
    }

    // 编辑
    const handleEdit = (scope:any) =>{
      add('EDIT',scope)
    }

    // 批量启用/禁用
    const batchChange = async (index?:any,row?:any) => {
      let ids:number[] = []
      if(row){
        ids = [row.id]
      }else{
        if(!selections.value.length){
          ElMessage({
            message:"请先选择数据",
            type:"warning"
          })
          return
        }
        ids = selections.value.map(item=>item.id)
      }
      let postData = {ids}
      const res = await changeStatusApi(postData)
      if(res.data.code === 1){
        ElMessage({
            message:"修改状态成功",
            type:"success"
          })
          reset()
      }
    }

    // 删除 批量删除
    const batchDel = async (index?:any,row?:any) => {
      let ids:number[] = []
      if(row){
        ids = [row.id]
      }else{
        if(!selections.value.length){
          ElMessage({
            message:"请先选择数据",
            type:"warning"
          })
          return
        }
        ids = selections.value.map(item=>item.id)
      }
      ElMessageBox.confirm(
        '确定删除？','删除用户',
        {confirmButtonText: '确定',cancelButtonText: '取消',type: 'error',}
      ).then(async () => {
        const postData = {ids}
        const res = await deleteUsersApi(postData)
        if(res.data.code === 1){
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          reset()
        }
      }).catch(() => {

      })
    }

    // 挂载
    onMounted(()=>{
      getTableHeight()
      getRoleList()
      getUserList()
    })

    return {
      ...toRefs(reactiveData),
      searchRef,btnsRef,pageRef,
      tableHeight,getTableHeight,getUserList,
      currentPage,pageSize,pageTotal,pageBackground,handleSizeChange,handleCurrentChange,
      search,reset,handleEdit,add,batchDel,batchChange,
      handleSelectionChange,
      addUserRef,
      getRoleNames
    }
  }
})
</script>

<style scoped lang="stylus">

</style>
